use crate::model::user::User;
use crate::service;
use crate::state::AppState;
use crate::{dto::user::UserRegisterRequest, error::AppError};
use axum::{extract::State, Json};
use std::sync::{Arc, Mutex};
use tracing::info;

#[axum::debug_handler]
pub async fn user_list(
    State(payload): State<Arc<Mutex<AppState>>>,
) -> Result<Json<Vec<User>>, AppError> {
    info!("user_listing");
    let app_state = payload.lock()?;
    let users = app_state.users.clone();

    Ok(Json(users))
}

pub async fn user_register(
    State(app_state): State<Arc<Mutex<AppState>>>,
    Json(req): Json<UserRegisterRequest>,
) -> Result<Json<Vec<User>>, AppError> {
    info!("user_registering");
    let mut app_state = app_state.lock()?;

    let mut users = app_state.users.clone();

    let user = service::user::user_register(users.clone(), req);

    users.push(user);

    // 更新 app_state 中的 users 向量
    app_state.users = users.clone();

    Ok(Json(users))
}
